#!/bin/sh -efu
#
# Check patching of repo $1 -> $2.
#
# Copyright (C) 2021 Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-or-later

srcdir="${srcdir=.}"
srcdir="$(realpath $srcdir)"
. "$srcdir/init.sh"

from="$1"; shift
to="$1"; shift
[ -n "$from" ]
[ -n "$to" ]

arch=test
repo_expected="$srcdir/$to.repo"

[ -d "$repo_expected/$arch" ]

copy_pkgs "$arch"
copy_base "$srcdir/$from.repo/$arch" "$repo/$arch"

check_prog find
if [ -n "${keep_compressed:-}" ]; then
	LIST_STEM='.*list\.[^\.]*'
	LISTS_REGEX=
	case "$keep_compressed" in
		none)
			LISTS_REGEX="$LIST_STEM"
			;;
		*)
			LISTS_REGEX="$LIST_STEM\.$keep_compressed"
			;;
	esac
	find "$repo/$arch" \
		-regextype posix-egrep \
		-'(' -name 'pkglist.*' \
		-or  -name 'srclist.*' \
		-')' \
		-printf '%y %p' \
		-'(' -regex "$LISTS_REGEX" -printf ' kept\n' \
		-or -printf ' deleted\n' -delete \
		-')'
fi
if [ -n "${add_spurious_old-}" ]; then
	for f in $(find "$repo/$arch" \
		-regextype posix-egrep \
		-regex '.*/(pkg|src)list\.[^\.]*' \
		-printf '%p.old\n'); do
		echo 'Spurious bad data for tests.' > "$f"
	done
fi

add_list="$srcdir/$from-$to".add-list
[ -s "$add_list" ] ||
	add_list=

rm_list="$srcdir/$from-$to".rm-list
[ -s "$rm_list" ] ||
	rm_list=

rc=0
$GENBASEDIR "$@" \
	--patch-basedir \
	${add_list:+--add-list $add_list} \
	${rm_list:+--rm-list $rm_list} \
	--create \
	--flat --mapi \
	--topdir "$repo" \
	--changelog-since=2009-01-01 \
	"$arch" || rc="$?"

if [ -n "${genbasedir_should_fail-}" ]; then
	if [ "$rc" = 0 ]; then
		exit 1
	else
		exit 0
	fi
else
	[ "$rc" = 0 ] ||
		exit "$rc"
fi

check_base "$arch"
